package velox.jcr.util;

import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Value;

public class NodeUtils {
	public static Node assertChild(Node n, String childName) throws RepositoryException {
		if (! n.hasNode(childName)) return n.addNode(childName);
		return n.getNode(childName);
	}

	public static void assertChildren(Node node, String... children) throws RepositoryException {
		for (String child : children) {
			assertChild(node, child);
		}
	}
	
	public static void dump(Node node) throws RepositoryException {
		// Skip the virtual (and large!) jcr:system subtree
		if (node.getName().equals("jcr:system")) {
			return;
		}

		// First output the node path
		System.out.println(node.getPath());

		// Then output the properties
		PropertyIterator properties = node.getProperties();
		while (properties.hasNext()) {
			Property property = properties.nextProperty();
			if (property.getName().equals("jcr:primaryType"))
				continue;
			if (property.getDefinition().isMultiple()) {
				// A multi-valued property, print all values
				Value[] values = property.getValues();
				for (int i = 0; i < values.length; i++) {
					System.out.println(property.getPath() + " = "
							+ values[i].getString());
				}
			} else {
				// A single-valued property
				System.out.println(property.getPath() + " = "
						+ property.getString());
			}
		}

		// Finally output all the child nodes recursively
		NodeIterator nodes = node.getNodes();
		while (nodes.hasNext()) {
			dump(nodes.nextNode());
		}
	}

	public static void removeAll(Node rootNode) throws RepositoryException {
		NodeIterator ni = rootNode.getNodes();
		while (ni.hasNext()) {
			Node n = ni.nextNode(); 
			if (! n.getName().startsWith("jcr:")) {
				n.remove();
			}
		}
	}
}
